#!/bin/bash

cp .githooks/pre-commit .git/hooks/pre-commit

# BaseApi Pre-Commit Hook
# Runs quality checks before allowing commits

# Colors for pretty output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
PURPLE='\033[0;35m'
CYAN='\033[0;36m'
NC='\033[0m' # No Color

# Unicode symbols
CHECK_MARK="✅"
CROSS_MARK="❌"
WARNING="⚠️"
ROCKET="🚀"
MAGNIFYING_GLASS="🔍"
GEAR="⚙️"

echo ""
echo -e "${PURPLE}${ROCKET} BaseApi Pre-Commit Quality Checks${NC}"
echo -e "${CYAN}═══════════════════════════════════════${NC}"
echo ""

# Track if any checks fail
FAILED=0

# Function to print step header
print_step() {
    echo -e "${BLUE}${MAGNIFYING_GLASS} $1${NC}"
    echo -e "${CYAN}───────────────────────────────${NC}"
}

# Function to print success
print_success() {
    echo -e "${GREEN}${CHECK_MARK} $1${NC}"
    echo ""
}

# Function to print error
print_error() {
    echo -e "${RED}${CROSS_MARK} $1${NC}"
    echo ""
    FAILED=1
}

# Function to print warning
print_warning() {
    echo -e "${YELLOW}${WARNING} $1${NC}"
    echo ""
}

# Check if we're in a git repository
if [ ! -d .git ]; then
    print_error "Not in a git repository"
    exit 1
fi

# Get list of staged PHP files
STAGED_FILES=$(git diff --cached --name-only --diff-filter=ACM | grep '\.php$')

# PHP Syntax Check
print_step "PHP Syntax Check"
SYNTAX_ERRORS=0
for file in $STAGED_FILES; do
    if [ -f "$file" ]; then
        php -l "$file" > /dev/null 2>&1
        if [ $? -ne 0 ]; then
            print_error "Syntax error in $file"
            php -l "$file"
            SYNTAX_ERRORS=1
        fi
    fi
done

if [ $SYNTAX_ERRORS -eq 0 ]; then
    print_success "All PHP files have valid syntax"
else
    FAILED=1
fi

# PHPStan Analysis
print_step "PHPStan Static Analysis"
if command -v composer > /dev/null 2>&1; then
    if composer phpstan > /dev/null 2>&1; then
        print_success "PHPStan analysis passed"
    else
        print_error "PHPStan analysis failed"
        echo -e "${YELLOW}Running PHPStan to show errors:${NC}"
        composer phpstan
        echo ""
    fi
else
    print_warning "Composer not found - skipping PHPStan"
fi

# PHPUnit
print_step "PHPUnit Tests"

if command -v composer > /dev/null 2>&1; then
    if composer phpunit > /dev/null 2>&1; then
        print_success "All PHPUnit tests passed"
    else
        print_error "Some PHPUnit tests failed"
        echo -e "${YELLOW}Running PHPUnit to show failures:${NC}"
        composer phpunit
        echo ""
    fi
else
    print_warning "Composer not found - skipping PHPUnit tests"
fi

# Check for common issues
print_step "Code Quality Checks"

# Check for var_dump, print_r, etc.
DEBUG_FUNCTIONS="var_dump\|print_r\|dump\|debug_print_backtrace"
DEBUG_FOUND=0
for file in $STAGED_FILES; do
    if [ -f "$file" ]; then
        if grep -n "$DEBUG_FUNCTIONS" "$file" > /dev/null; then
            if [ $DEBUG_FOUND -eq 0 ]; then
                print_error "Debug functions found in staged files:"
                DEBUG_FOUND=1
            fi
            echo -e "${RED}  • $file:${NC}"
            grep -n --color=always "$DEBUG_FUNCTIONS" "$file" | sed 's/^/    /'
        fi
    fi
done

# Check for TODO/FIXME comments in staged files
TODO_FOUND=0
for file in $STAGED_FILES; do
    if [ -f "$file" ]; then
        if grep -n "TODO\|FIXME\|XXX\|HACK" "$file" > /dev/null; then
            if [ $TODO_FOUND -eq 0 ]; then
                echo -e "${YELLOW}${WARNING} TODO/FIXME comments found:${NC}"
                TODO_FOUND=1
            fi
            echo -e "${YELLOW}  • $file:${NC}"
            grep -n --color=always "TODO\|FIXME\|XXX\|HACK" "$file" | sed 's/^/    /'
        fi
    fi
done

if [ $DEBUG_FOUND -eq 0 ] && [ $TODO_FOUND -eq 0 ]; then
    print_success "Code quality checks passed"
elif [ $DEBUG_FOUND -eq 1 ]; then
    echo ""
fi

if [ $TODO_FOUND -eq 1 ]; then
    echo ""
fi

# File size check
print_step "File Size Check"
LARGE_FILES=0
for file in $STAGED_FILES; do
    if [ -f "$file" ]; then
        SIZE=$(wc -c < "$file")
        if [ $SIZE -gt 50000 ]; then  # 50KB
            if [ $LARGE_FILES -eq 0 ]; then
                print_warning "Large files detected:"
                LARGE_FILES=1
            fi
            echo -e "${YELLOW}  • $file ($(echo "scale=1; $SIZE/1024" | bc)KB)${NC}"
        fi
    fi
done

if [ $LARGE_FILES -eq 0 ]; then
    print_success "All files are reasonably sized"
else
    echo ""
fi

# Final result
echo -e "${CYAN}═══════════════════════════════════════${NC}"
if [ $FAILED -eq 1 ]; then
    echo -e "${RED}${CROSS_MARK} Pre-commit checks failed!${NC}"
    echo -e "${YELLOW}Please fix the issues above before committing.${NC}"
    echo ""
    exit 1
else
    echo -e "${GREEN}${CHECK_MARK} All pre-commit checks passed!${NC}"
    echo -e "${GREEN}${ROCKET} Ready for commit${NC}"
    echo ""
    exit 0
fi

